package com.icss.ah.base.util;

import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.State;
import com.icss.ah.base.util.ResourceLoader;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.io.FileUtils;

public class StorageManager {
	public static final int BUFFER_SIZE = 8192;

	public static State saveBinaryFile(byte[] data, String path) {
		File file = new File(path);

		State state = valid(file);

		if (!state.isSuccess()) {
			return state;
		}
		try {
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(file));
			bos.write(data);
			bos.flush();
			bos.close();
		} catch (IOException ioe) {
			return new BaseState(false, 4);
		}

		state = new BaseState(true, file.getAbsolutePath());
		state.putInfo("size", data.length);
		state.putInfo("title", file.getName());
		return state;
	}

	public static State saveFileByInputStream(HttpServletRequest request, InputStream is, String path,
			long maxSize) {
		State state = null;
		try {
			String uploadUrl = ResourceBundle.getBundle("icss").getString("uploadUrl");
			String fileName = "DATE"+path.substring(path.lastIndexOf("=") + 1);
			String fileExt = fileName.substring(fileName.lastIndexOf("."), fileName.length());
			String imageUrl = HttpFileUtil.uploadFileHttp(is, uploadUrl, "B2B", fileExt);
			state = new BaseState(true);
			state.putInfo("url", imageUrl );
		} catch (Exception e) {
			e.printStackTrace();
		}
		return state;
	}
	/*
	public static State saveFileByInputStream(HttpServletRequest request, InputStream is, String path,
			long maxSize) {
		State state = null;

		File tmpFile = getTmpFile();

		byte[] dataBuf = new byte[2048];
		BufferedInputStream bis = new BufferedInputStream(is, 8192);
		try {
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(tmpFile), 8192);

			int count = 0;
			while ((count = bis.read(dataBuf)) != -1) {
				bos.write(dataBuf, 0, count);
			}
			bos.flush();
			bos.close();

			if (tmpFile.length() > maxSize) {
				tmpFile.delete();
				return new BaseState(false, 1);
			}
			//      state = saveTmpFile(tmpFile, path);
			*//******************//*
			try {
				String flag = request.getParameter("flag");
				flag = flag == null ? "" : flag;
				System.out.println("=====86=="+path);
					String newFileName = "DATE"+path.substring(path.lastIndexOf("=") + 1);
					if(flag.equals("up")){
						newFileName = newFileName.substring(0, newFileName.lastIndexOf("."))+".jpg";
//						tmpFile.renameTo(new File(newFileName));
					}
					String uploadImgUrl = ResourceLoader.getInstance("weixin").getString("uploadImgUrl");
					String imageUrl = ResourceLoader.getInstance("weixin").getString("imageUrl");
					PostMethod filePost = new PostMethod(uploadImgUrl+"?uploadFlag=only");

					Part[] parts = { new FilePart(newFileName, tmpFile) };
					filePost.setParameter("newFileName", newFileName);
					filePost.setRequestEntity(new MultipartRequestEntity(parts,
							filePost.getParams()));
					HttpClient client = new HttpClient();
					client.getHttpConnectionManager().getParams()
							.setConnectionTimeout(2000);
					int status = client.executeMethod(filePost);
					*//*****压缩图片*****//*
//					ImgCompressUtil.compressImg(newFileName, path.substring(0,path.lastIndexOf("=")+1));
					*//*****************//*
					if (status == HttpStatus.SC_OK) {
						System.out.println("===107==上传成功:" + newFileName);
						state = new BaseState(true);
						state.putInfo("url", imageUrl + newFileName);
					} else {
						state = new BaseState(false);
						System.out.println("上传失败");
					}
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (!state.isSuccess()) {
				tmpFile.delete();
			}
			return state;
		} catch (IOException localIOException) {
		}
		return new BaseState(false, 4);
	}*/

	/*public static String setMediaBean(String accessToken,String corpType, String imgUrl) throws Exception{
		String picUrl = "";
		String url = imgUrl;
		String fileExt = url.substring(url.lastIndexOf("."), url.length());
		String uploadUrl = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN";
		JSONObject json = wxUtils.uploadMediaUrl(accessToken,uploadUrl, corpType, imgUrl, fileExt);
		System.out.println("=============json:"+json.toString());
		if(json.getString("url")==null){
			throw new Exception("上传图文信息图片失败|错误码"+json.getString("errcode")+"|错误信息"+json.getString("errmsg"));
		} else {
			picUrl = json.getString("url");
			System.out.println("===============picUrl:"+picUrl);
		}
		return picUrl;
	}
	 public static State saveFileByInputStream(InputStream is, String path, long maxSize)
	 {
	 State state = null;

	 File tmpFile = getTmpFile();

	 byte[] dataBuf = new byte[2048];
	 BufferedInputStream bis = new BufferedInputStream(is, 8192);
	 try
	 {
	 BufferedOutputStream bos = new BufferedOutputStream(
	 new FileOutputStream(tmpFile), 8192);

	 int count = 0;
	 while ((count = bis.read(dataBuf)) != -1) {
	 bos.write(dataBuf, 0, count);
	 }
	 bos.flush();
	 bos.close();

	 if (tmpFile.length() > maxSize) {
	 tmpFile.delete();
	 return new BaseState(false, 1);
	 }

	 //      state = saveTmpFile(tmpFile, path);
	 try {
	 String path1 = "/eWebEditor/uploads";
	 System.out.println("========StorageManager-77====2=====path:"+path);
	 //改为FTP方式存文件
	 String IP = "10.49.0.6";
	 int port = 21;
	 String userName = "ftpUser";
	 String userPassword = "hfyc";
	 FtpUtil ftp = new FtpUtil();
	 //链接FTP
	 FtpClient fc = ftp.ftpConnection(IP, port, userName, userPassword);
	 String photoName = path.substring(path.lastIndexOf("/")+1);
	 //			System.out.println("===name:"+name);
	 //String photoName = new UUID().toString()+".jpg";;
	 InputStream iStream = new FileInputStream(tmpFile);
	 ftp.ftpPut(fc, path1 + "/" + photoName, iStream);
	 System.out.println("=====StorageManager-89==============");
	 state = new BaseState(true);
	 } catch (Exception e) {
	 // TODO Auto-generated catch block
	 e.printStackTrace();
	 }
	 

	 if (!state.isSuccess()) {
	 tmpFile.delete();
	 }

	 return state;
	 }
	 catch (IOException localIOException) {
	 }
	 return new BaseState(false, 4);
	 }
	 */
	public static State saveFileByInputStream(InputStream is, String path) {
		State state = null;

		File tmpFile = getTmpFile();

		byte[] dataBuf = new byte[2048];
		BufferedInputStream bis = new BufferedInputStream(is, 8192);
		try {
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(tmpFile), 8192);

			int count = 0;
			while ((count = bis.read(dataBuf)) != -1) {
				bos.write(dataBuf, 0, count);
			}
			bos.flush();
			bos.close();

			state = saveTmpFile(tmpFile, path);

			if (!state.isSuccess()) {
				tmpFile.delete();
			}

			return state;
		} catch (IOException localIOException) {
		}
		return new BaseState(false, 4);
	}

	private static File getTmpFile() {
		File tmpDir = FileUtils.getTempDirectory();
		String tmpFileName = (Math.random() * 10000.0D + "").replace(".", "");
		return new File(tmpDir, tmpFileName);
	}

	private static State saveTmpFile(File tmpFile, String path) {
		State state = null;
		File targetFile = new File(path);

		if (targetFile.canWrite())
			return new BaseState(false, 2);
		try {
			FileUtils.moveFile(tmpFile, targetFile);
		} catch (IOException e) {
			return new BaseState(false, 4);
		}

		state = new BaseState(true);
		state.putInfo("size", targetFile.length());
		state.putInfo("title", targetFile.getName());

		return state;
	}

	private static State valid(File file) {
		File parentPath = file.getParentFile();

		if ((!parentPath.exists()) && (!parentPath.mkdirs())) {
			return new BaseState(false, 3);
		}

		if (!parentPath.canWrite()) {
			return new BaseState(false, 2);
		}

		return new BaseState(true);
	}
}